import { computed } from 'vue'
import { useUserStore } from '@/stores/user'
import { login, register } from '@/api/user'
import { fetUserInfo } from '@/api/game'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ILoginInfo } from '@/types'

export function useAuth() {
  const store = useUserStore()
  const user = computed(() => store.getUserInfo)

  const userRegister = async (data: ILoginInfo) => {
    const res = await register(data)
    console.log(res)

    let userInfo = {
      user_id: res.user_id,
      username: res.username,
      currency: res.currency,
      token: res.token,
    }
    store.setInfo({ token: res.token, userInfo: userInfo })
    return res
  }

  const userLogin = async (data: ILoginInfo) => {
    const res = await login(data)
    let userInfo = {
      user_id: res.user_id,
      username: res.username,
      currency: res.currency,
      token: res.token,
    }
    console.log(userInfo)

    store.setInfo({ token: res.token, userInfo: userInfo })
    return res
  }

  const hangdleUserInfo = async () => {
    try {
      let res = await fetUserInfo({})

      let userInfo = {
        user_id: res.user_id,
        username: res.username,
        currency: res.currency,
      }
      console.log(userInfo)

      store.setInfo({ token: null, userInfo: userInfo })
    } catch (err) {
      if (err.code == 400) {
        open()
      }
    }
  }
  const open = () => {
    ElMessageBox.alert('用户登录已过期', '标题', {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: 'OK',
      callback: async () => {
        await logout()
        location.reload()
      },
    })
  }
  const logout = () => {
    let userInfo = {
      user_id: '',
      username: '',
      currency: '',
    }
    store.setInfo({ token: null, userInfo: userInfo }) // sessionStorage.removeItem('HYnavtab')
    store.removeInfo()
  }
  return {
    user,
    userLogin,
    logout,
    userRegister,
    hangdleUserInfo,
  }
}
